package hanshunping.project.chatRoom.chatServer.server.service;

import hanshunping.project.chatRoom.common.Message;
import hanshunping.project.chatRoom.common.MessageType;

import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ConnectThread extends Thread{
    private Socket socket;
    private String userId;

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public ConnectThread(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    public ConnectThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        out: while (true){
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message ms = (Message) ois.readObject();
                switch (ms.getMesType()) {
                    case MessageType.MESSAGE_ONLINE:
                        System.out.println("用户："+ms.getSender()+"请求获取用户列表");
                        Message msOnlines = new Message();
                        msOnlines.setGetter(ms.getSender());
                        msOnlines.setContent(ManageConnectThread.getOnlines());
                        msOnlines.setMesType(MessageType.MESSAGE_RETURN_ONLINE);
                        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                        oos.writeObject(msOnlines);
                        break;
                    case MessageType.MESSAGE_EXIT:
                        System.out.println("用户："+ms.getSender()+"退出");
                        ManageConnectThread.removeThread(ms.getSender());
                        socket.close();
                        break out;
                    case MessageType.MESSAGE_MES:
                        System.out.println(ms.getSender()+"对"+ms.getGetter()+"说："+ms.getContent());
                        ObjectOutputStream oos2 = new ObjectOutputStream(ManageConnectThread.getThread(ms.getGetter()).getSocket().getOutputStream());
                        oos2.writeObject(ms);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}
